package com.yy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yy.entities.CommonResult;
import com.yy.pojo.Student;
import com.yy.service.StudentService;
import com.yy.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileUploadController {

    @Autowired
    private StudentService studentService;


    // 文件上传到本地磁盘
/*    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) {
        if(file!=null){
            try {
                file.transferTo(new File("D:\\img\\"+file.getOriginalFilename()));
                return Result.success("上传成功");
            }catch (Exception e) {
                e.printStackTrace();
                return Result.error("上传失败");
            }
        }
        return Result.error("上传失败");
    }*/

    // 文件上传到阿里云
    @PostMapping("/upload/{studentId}")
    public CommonResult upload( MultipartFile file,@PathVariable Integer studentId) throws Exception {
        // 拿到文件的名字
        String fileName = file.getOriginalFilename();
        // 使用UUID生成唯一的文件名
        String uuidFileName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
        String url = AliOssUtil.uploadFile(uuidFileName,file.getInputStream());
        Student student = new Student();
        student.setStudentPic(url);
        studentService.update(student,new QueryWrapper<Student>().eq("student_id",studentId));
        return new CommonResult(200,"成功",url);
    }
}
